const {isString} = require('./dataType')

let postfix = '_deadtime';
const storage = {
    save(key, value, time) {
        if (!isString(key) || !value) {
            throw new Error(415)
        }
        wx.setStorageSync(key, JSON.stringify(value))
        var t = time ? time : 24 * 30;
        var seconds = parseInt(t * 3600);
        if (seconds > 0) {
            var timestamp = Date.parse(new Date());
            timestamp = timestamp / 1000 + seconds;
            wx.setStorageSync(key + postfix, timestamp + "")
        } else {
            wx.removeStorageSync(key + postfix)
        }
    },
    fetch(key, def) {
        if (!isString(key)) {
            throw new Error(415)
        }
        var deadtime = parseInt(wx.getStorageSync(key + postfix))
        if (deadtime) {
            if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
                wx.removeStorageSync(key);
                wx.removeStorageSync(key + postfix);
                if (def) {
                    return def;
                } else {
                    return;
                }
            }
        }
        var res = wx.getStorageSync(key);
        if (res) {
            return res;
        } else if (def) {
            return def;
        } else {
            return;
        }
    },
    remove(key) {
        if (!isString(key)) {
            throw new Error(415)
        }
        return wx.removeStorageSync(key)
    },
    clear() {
        return wx.clearStorageSync()
    }
}
module.exports = storage